package com.able.concurrency.t2;

import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author abel.he
 * @data 2018/8/18 14:47
 * @describe
 */
public class Test5_2<E> {

    private LinkedList<E> linkedList = new LinkedList<E>();
    final int MAX = 10;

    private Lock lock = new ReentrantLock();
    Condition consumer = lock.newCondition();
    Condition producer =lock.newCondition();

    void put(E data) {
        try {
            lock.lock();
            while (linkedList.size() == MAX) {
                producer.await();
            }
            linkedList.add(data);
            consumer.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    E get() {
        E result = null;
        try {
            lock.lock();
            while (linkedList.size() == 0) {
                consumer.await();
            }
            result = linkedList.removeFirst();
            producer.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return result;
    }

    public static void main(String[] args) {
        final Test5_2<String> test52 = new Test5_2<String>();
        for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 5; j++) {
                        System.out.println(Thread.currentThread().getName() + " data: " + test52.get());
                    }
                }
            }, "consumer " + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(new Runnable() {
                public void run() {
                    for (int j = 0; j < 25; j++) {
                        test52.put(Thread.currentThread().getName() + "-" + j);
                    }
                }
            }, "producer" + i).start();
        }
    }

}
